package va_file;

import bufmgr.HashEntryNotFoundException;
import bufmgr.InvalidFrameNumberException;
import bufmgr.PageNotReadException;
import bufmgr.PageUnpinnedException;
import bufmgr.ReplacerException;
import global.*;
import heap.*;
import index.IndexException;
import iterator.CondExpr;
import iterator.FileScanException;
import iterator.FldSpec;
import iterator.InvalidRelation;
import iterator.JoinsException;
import iterator.PredEvalException;
import iterator.SortException;
import iterator.TupleUtilsException;
import iterator.UnknowAttrType;
import iterator.WrongPermat;
import va.BaseIndexScan;
import va.VAEntry;

import java.io.IOException;

public class VAFileIndexScan extends BaseIndexScan {

    public VAFileScan scanner;

    public VAFileIndexScan(IndexType index,
                           String relName,
                           String indexName,
                           AttrType[] types,
                           short[] str_sizes,
                           int noInFields,
                           int noOutFields,
                           FldSpec[] outFields,
                           CondExpr[] selects,
                           int fldNum) throws IndexException, HFException, HFBufMgrException, HFDiskMgrException, IOException, InvalidTupleSizeException, InvalidTypeException, FileScanException, TupleUtilsException, InvalidRelation, JoinsException, PageNotReadException, PredEvalException, UnknowAttrType, FieldNumberOutOfBoundException, WrongPermat {
        super(index, relName, indexName, types, str_sizes, noInFields, noOutFields, outFields, selects, fldNum);
        VAFile file = new VAFile(indexName);
        this.scanner = file.openVAScan();
    }

    // Grabs the next rid and its corresponding tuple from the data set
    // This is just a simple scan of the VA Heap File

    @Override
    public Tuple get_next() throws Exception {
        VAEntry entry = this.scanner.getNextHeapVA();
        if (entry == null) {
            return null;
        }
        RID rid = entry.rid;
        Tuple tuple = getRecordDirect(rid);
        return this.formatTuple(tuple);
    }

    // Closes the scanner to prevent against pinned buffer pages being left

    @Override
    public void close() throws IOException, JoinsException, SortException,
            IndexException, PageUnpinnedException, InvalidFrameNumberException, HashEntryNotFoundException, ReplacerException {
        super.close();
        this.scanner.close();
    }
}
